const app = getApp();
let transformState = {
  rotation: 0, // 当前旋转角度（弧度）
  scale: 1,    // 当前缩放比例
};
Page({
  data: {
    code: '',
    isVerified: false,
    verificationId: null,
    expireAt: null,
    images: [],
    cropperVisible: false,
    cropperImageSrc: null,
    currentImage: null,
    isMobile: false,
    isCropping: false,
    originalImage: null, // 新增字段
    cropRect: { x: 0, y: 0, width: 300, height: 300 }, // 裁剪区域信息
    cropBox: { x: 75, y: 75, width: 150, height: 150 }, // 裁剪框位置和尺寸
    isDragging: false,
    dragMode: 'move', // move / resize
    dragStart: null,
  },

  onLoad() {
    this.setData({ isMobile: wx.getWindowInfo().windowWidth <= 768 });
  },

  onCodeChange(e) {
    this.setData({ code: e.detail.value });
  },

  submitCode() {
    try{
      app.request({
        url:'/user/verification/imageUpload/' + this.data.code, 
        success:(res) =>{
          if (res.code !== 1) throw new Error(res.msg);
          const { id, expireAt, imageList } = res.data;
          // 添加 imageUrl 到每张图片
        const imagesWithUrl = (imageList || []).map(img => ({
          ...img,
          imageUrl: this.getImageUrl(img.id)
        }));

        this.setData({
          verificationId: id,
          expireAt: expireAt,
          isVerified: true,
          images: imagesWithUrl
        });
          wx.showToast({ title: "验证码正确", icon: 'success' });
        },
        fail: (err) => {
          wx.showToast({ title: '请求失败', icon: 'none' });
          console.error(err);
        }
      })
    }catch (e) {
      wx.showToast({ title: "验证码错误"+e.message, icon: 'none' });
    }
    
  },

  chooseImage() {
    wx.chooseImage({
      count: 9,
      success: (res) => {
        this.handleFileChange(res.tempFilePaths);
      },
    });
  },

  handleFileChange(filePaths) {
    for (let filePath of filePaths) {
      try {
        const formData = {
          verificationId: this.data.verificationId,
        };
        app.request({
          url: '/user/minio/userUploadImage',
          isUpload: true, // 标记为上传请求
          filePath: filePath,
          fileName: 'file', // 后端接收的字段名
          formData: formData,
          success: (res) => {
            if (res.code !== 1) throw new Error(res.msg);
            // 添加 imageUrl 到新上传的图片
            const updatedImage = {
              ...res.data,
              imageUrl: this.getImageUrl(res.data.id)
            };
            this.setData({ images: [...this.data.images, updatedImage] });
            wx.showToast({ title: `${filePath} 上传成功`, icon: 'success' });
          },
          fail: (err) => {
            wx.showToast({ title: '上传失败', icon: 'none' });
            console.error(err);
          }
        });
      } catch (e) {
        wx.showToast({ title: "上传失败：" + e.message, icon: 'none' });
      }
    }
  },
  editImage(e) {
    const index = e.currentTarget.dataset.index;
    const image = this.data.images[index];
    
    wx.getImageInfo({
      src: image.imageUrl,
      success: (res) => {
        transformState = {
          rotation: 0,
          scale: 1
        };
  
        this.setData({
          cropperImageSrc: res.path,
          originalImage: res.path,
          currentImage: image,
          cropperVisible: true
        });
  
        setTimeout(() => {
          const ctx = wx.createCanvasContext('cropper');
          ctx.drawImage(res.path, 0, 0, 300, 300);
          ctx.draw();
        }, 500);
      }
    });
  },

  cropAndUpload() {
    try {
      const { cropBox } = this.data;
  
      wx.canvasToTempFilePath({
        x: cropBox.x,
        y: cropBox.y,
        width: cropBox.width,
        height: cropBox.height,
        destWidth: cropBox.width,
        destHeight: cropBox.height,
        canvasId: 'cropper',
        success: (res) => {
          const formData = {
            id: this.data.currentImage.id,
            minioName: this.data.currentImage.minioName,
          };
  
          app.request({
            url: '/user/minio/userUploadImage',
            isUpload: true,
            filePath: res.tempFilePath,
            fileName: 'file',
            formData: formData,
            success: (response) => {
              if (response.code !== 1) throw new Error(response.msg);
              // 添加 imageUrl 到新上传的图片
              const updatedImage = {
                ...response.data,
                imageUrl: this.getImageUrl(response.data.id)
              };
              // 更新 images 数组中的对应图片
              const updatedImages = this.data.images.map(img =>
                img.id === updatedImage.id ? updatedImage : img
              );
              this.setData({ images: updatedImages });
              this.closeCropper();
              wx.showToast({ title: "图片更新成功", icon: 'success' });
            },
            fail: (err) => {
              wx.showToast({ title: '请求失败', icon: 'none' });
              console.error(err);
            }
          });
        }
      });
    } catch (error) {
      wx.showToast({ title: "操作失败: " + error.message, icon: 'none' });
    }
  },
  closeCropper() {
    this.setData({
      cropperVisible: false,
      cropperImageSrc: null,
      originalImage: null,
    });
  },

  deleteImage(e) {
    const index = e.currentTarget.dataset.index;
    const image = this.data.images[index];
    wx.showModal({
      title: '提示',
      content: '确定要删除这张图片吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            app.request({
              url:`/user/minio/deleteImage/${image.id}`, method:'DELETE'
            });
            const updatedImages = this.data.images.filter((_, idx) => idx !== index);
            this.setData({ images: updatedImages });
            wx.showToast({ title: "删除成功", icon: 'success' });
          } catch (error) {
            wx.showToast({ title: "删除失败: " + error.message, icon: 'none' });
          }
        }
      }
    });
  },

  rotate(e) {
    const deg = Number(e.currentTarget.dataset.deg);
    transformState.rotation += deg * Math.PI / 180; // 转换为弧度
  
    this.redrawImage();
  },
  
  zoom(e) {
    const percent = Number(e.currentTarget.dataset.percent);
    transformState.scale *= (1 + percent);
  
    this.redrawImage();
  },
  
  redrawImage() {
    if (!this.data.originalImage) return;
  
    const ctx = wx.createCanvasContext('cropper');
    const { originalImage } = this.data;
    const { rotation, scale } = transformState;
  
    // 清空画布并重绘
    ctx.clearRect(0, 0, 300, 300);
  
    // 设置中心点旋转
    ctx.translate(150, 150);        // 移动到中心点
    ctx.rotate(rotation);           // 应用旋转
    ctx.scale(scale, scale);        // 应用缩放
    ctx.drawImage(originalImage, -150, -150, 300, 300); // 从中心绘制图片
  
    ctx.restore(); // 恢复上下文状态
    ctx.draw();
  },
  getImageUrl(imgId) {
    return `${app.globalData.apiUrl}/user/minio/getImage/${imgId}?t=${Date.now()}_${Math.random().toString(36).substr(2, 5)}`;
  },

  goHome() {
    wx.redirectTo({
      url: '/pages/user/UserHomeView/UserHomeView'
    });
  },

  submitOrder() {
    const { images, verificationId } = this.data;
    const imageIdList = images.map(img => img.id);
  
    try{
        app.request({
        url:'/user/order/createOrder', 
        method:'POST', 
        data:{
          imageIdList: imageIdList,
          verificationId: verificationId || null
        },
        success:(res)=>{
          if (res.code !== 1) throw new Error(res.msg);
          wx.showToast({ title: "提交成功", icon: 'success' });
          // 清空页面状态
          this.resetForm();
        },
        fail: (err) => {
          wx.showToast({ title: '请求失败', icon: 'none' });
          console.error(err);
        }
      })
    }catch (e) {
      wx.showToast({ title: "提交失败：" + e.message, icon: 'none' });
    }
  },
  
  resetForm() {
    this.setData({
      images: [],
      verificationId: null,
      expireAt: null,
      isVerified: false,
      code: ''
    });
  },
  // 记录初始位置和裁剪框信息
  onTouchStart(e) {
    const touch = e.touches[0];
    const { x, y } = touch;
  
    const { cropBox } = this.data;
  
    // 判断是否点击了中点或角落
    const target = e.target.dataset;
  
    let dragMode = 'move';
  
    if (target && target.handle) {
      dragMode = `resize-${target.handle}`;
    } else {
      // 原有逻辑：判断是否点击的是角落
      const edgeThreshold = 10;
      const edgeRight = cropBox.x + cropBox.width - edgeThreshold;
      const edgeBottom = cropBox.y + cropBox.height - edgeThreshold;
  
      if (x > edgeRight && y > edgeBottom) dragMode = 'resize-br';
      else if (x < cropBox.x + edgeThreshold && y < cropBox.y + edgeThreshold) dragMode = 'resize-tl';
      else if (x > edgeRight && y < cropBox.y + edgeThreshold) dragMode = 'resize-tr';
      else if (x < cropBox.x + edgeThreshold && y > edgeBottom) dragMode = 'resize-bl';
      else if (x > edgeRight) dragMode = 'resize-right';
      else if (y > edgeBottom) dragMode = 'resize-bottom';
      else if (x < cropBox.x + edgeThreshold) dragMode = 'resize-left';
      else if (y < cropBox.y + edgeThreshold) dragMode = 'resize-top';
      else if (
        x >= cropBox.x &&
        x <= cropBox.x + cropBox.width &&
        y >= cropBox.y &&
        y <= cropBox.y + cropBox.height
      ) {
        dragMode = 'move';
      }
    }
  
    this.setData({
      isDragging: true,
      dragMode,
      dragStart: { x, y },
    });
  },

  onTouchMove(e) {
    if (!this.data.isDragging) return;
  
    const touch = e.touches[0];
    const dx = touch.x - this.data.dragStart.x;
    const dy = touch.y - this.data.dragStart.y;
  
    const { cropBox } = this.data;
  
    let newBox = { ...cropBox };
  
    switch (this.data.dragMode) {
      case 'move':
        newBox.x += dx;
        newBox.y += dy;
        break;
  
      // 角点
      case 'resize-br':
        newBox.width += dx;
        newBox.height += dy;
        break;
      case 'resize-tl':
        newBox.x += dx;
        newBox.y += dy;
        newBox.width -= dx;
        newBox.height -= dy;
        break;
      case 'resize-tr':
        newBox.y += dy;
        newBox.width += dx;
        newBox.height -= dy;
        break;
      case 'resize-bl':
        newBox.x += dx;
        newBox.width -= dx;
        newBox.height += dy;
        break;
  
      // 边缘中点
      case 'resize-top':
        newBox.y += dy;
        newBox.height -= dy;
        break;
      case 'resize-right':
        newBox.width += dx;
        break;
      case 'resize-bottom':
        newBox.height += dy;
        break;
      case 'resize-left':
        newBox.x += dx;
        newBox.width -= dx;
        break;
    }
  
    // 限制最小尺寸
    newBox.width = Math.max(50, newBox.width);
    newBox.height = Math.max(50, newBox.height);
  
    // 限制边界
    newBox.x = Math.max(0, Math.min(newBox.x, 300 - newBox.width));
    newBox.y = Math.max(0, Math.min(newBox.y, 300 - newBox.height));
  
    this.setData({
      cropBox: newBox,
      dragStart: { x: touch.x, y: touch.y }
    });
  },

  onTouchEnd() {
    this.setData({ isDragging: false });
  },
});